<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>员工列表</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="js/jquery-3.6.0.js"></script>
    <style>
        /* 分页导航水平居中 */
        #pageNav {
            display: flex;
            justify-content: center;
            width: 100%;
        }

        /* 添加到现有的style标签中 */
        #addModal {
            overflow: hidden; /* 禁止整个模态框滚动 */
        }

        #addModal > div > div { /* 模态框内容容器 */
            max-height: 80vh; /* 最大高度为视口的80% */
            overflow-y: auto; /* 内容超出时显示垂直滚动条 */
            display: flex;
            flex-direction: column;
        }

        /* 确保头像预览容器正确显示 */
        #editAvatarPreview {
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden; /* 确保圆角效果不被裁剪 */
        }

        /* 文字和图标居中 */
        #editAvatarPreview .text-center {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        /* 图片预览样式 */
        #editAvatarPreview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

    </style>
</head>
<body class="bg-white">
    <!-- 顶部操作栏 -->
    <div class="flex justify-between items-center mb-6 p-4">
        <div class="relative flex items-center">
            <i class="fas fa-search absolute left-3 pointer-events-none text-gray-400"></i>
            <input type="text" class="pl-10 w-full py-2 border rounded-lg" placeholder="搜索..." id="searchEmpName">
        </div>
        <button onclick="openAddModal()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
            <i class="fas fa-plus mr-2"></i>添加员工
        </button>
    </div>

    <!-- 员工列表 -->
    <div class="bg-white rounded-lg shadow">
        <div class="p-4 border-b">
            <h3 class="text-lg font-semibold">员工列表</h3>
        </div>
        <div class="overflow-x-auto">
            <table class="min-w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">员工ID</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">姓名</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">部门</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">职位</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">入职日期</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">头像</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">联系方式</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">

                </tbody>
            </table>
        </div>
        
        <!-- 分页 -->
        <div class="flex items-center justify-between px-4 py-3 bg-white border-t border-gray-200 sm:px-6">
            <ul class="pagination justify-content-center mb-0" id="pageNav">
                <!-- 分页将通过JavaScript动态加载 -->
            </ul>
        </div>
    </div>

    <!-- 添加员工模态框 -->
    <div id="addModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 hidden overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-white rounded-lg shadow-xl w-full max-w-md max-h-[80vh] flex flex-col">
                <!-- 模态框头部 -->
                <div class="flex justify-between items-center p-4 border-b">
                    <h3 class="text-lg font-semibold">添加员工</h3>
                    <button onclick="closeAddModal()" class="text-gray-400 hover:text-gray-500">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <!-- 模态框主体（可滚动区域） -->
                <div class="p-4 overflow-y-auto flex-1">
                    <form>
                        <!-- 头像上传 -->
                        <div class="mb-4 flex flex-col items-center">
                            <div class="relative w-32 h-32 mb-4">
                                <div id="avatarPreview" class="w-full h-full rounded-full bg-gray-200 flex items-center justify-center">
                                    <i class="fas fa-user text-gray-400 text-6xl"></i>
                                </div>
                                <label for="avatar" class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-50 rounded-full opacity-0 hover:opacity-100 transition-opacity duration-300 cursor-pointer">
                                    <i class="fas fa-camera text-white text-2xl"></i>
                                </label>
                                <input type="file" id="avatar" accept="image/*" class="hidden" onchange="previewAvatar(this)">
                            </div>
                            <p class="text-sm text-gray-500">点击头像上传新照片</p>
                        </div>
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-bold mb-2" for="name" >
                                姓名
                            </label>
                            <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="name" type="text" placeholder="请输入姓名">
                        </div>
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-bold mb-2" for="department">
                                部门
                            </label>
                            <select class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="department">

                            </select>
                        </div>
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-bold mb-2" for="position">
                                职位
                            </label>
                            <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="position" type="text" placeholder="请输入职位">
                        </div>
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-bold mb-2" for="joinDate">
                                入职日期
                            </label>
                            <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="joinDate" type="date">
                        </div>
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-bold mb-2" for="phone">
                                联系方式
                            </label>
                            <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="phone" type="text">
                        </div>
                    </form>
                </div>
                <div class="flex justify-end p-4 border-t">
                    <button onclick="closeAddModal()" class="bg-gray-500 text-white px-4 py-2 rounded-lg hover:bg-gray-600 mr-2">
                        取消
                    </button>
                    <button onclick="saveEmployee()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                        保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑员工模态框 -->
    <div id="editModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 hidden overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen p-4">
            <div class="bg-white rounded-lg shadow-xl w-full max-w-md max-h-[80vh] flex flex-col">
                <!-- 模态框头部 -->
                <div class="flex justify-between items-center p-4 border-b">
                    <h3 class="text-lg font-semibold">编辑员工</h3>
                    <button onclick="closeEditModal()" class="text-gray-400 hover:text-gray-500">
                        <i class="fas fa-times"></i>
                    </button>
                </div>

                <!-- 模态框主体（可滚动区域） -->
                <div class="p-4 overflow-y-auto flex-1">
                    <form>
                        <!-- 头像上传 -->
                        <div class="mb-4 flex flex-col items-center">
                            <div class="relative w-32 h-32 mb-4">
                                <label for="editAvatar" class="w-full h-full block">
                                    <div id="editAvatarPreview" class="w-full h-full rounded-full bg-gray-100 border-2 border-dashed border-gray-300 flex items-center justify-center cursor-pointer">
                                        <div class="text-center">
                                            <i class="fas fa-camera text-gray-400 text-2xl mb-2"></i>
                                            <p class="text-sm text-gray-500">点击头像修改照片</p>
                                        </div>
                                    </div>
                                </label>
                                <input type="file" id="editAvatar" accept="image/*" class="hidden" onchange="previewEditAvatar(this)">
                            </div>
                        </div>
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-bold mb-2" for="editName">
                                姓名
                            </label>
                            <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="editName" type="text">
                        </div>
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-bold mb-2" for="editDepartment">
                                部门
                            </label>
                            <select class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="editDepartment">
                                <!-- 动态加载部门选项 -->
                            </select>
                        </div>
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-bold mb-2" for="editPosition">
                                职位
                            </label>
                            <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="editPosition" type="text">
                        </div>
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-bold mb-2" for="editJoinDate">
                                入职日期
                            </label>
                            <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="editJoinDate" type="date">
                        </div>
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-bold mb-2" for="editPhone">
                                联系方式
                            </label>
                            <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="editPhone" type="text">
                        </div>
                    </form>
                </div>
                <div class="flex justify-end p-4 border-t">
                    <button onclick="closeEditModal()" class="bg-gray-500 text-white px-4 py-2 rounded-lg hover:bg-gray-600 mr-2">
                        取消
                    </button>
                    <button onclick="updateEmployee()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                        保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div id="deleteModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 hidden">
        <div class="flex items-center justify-center min-h-screen">
            <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
                <div class="p-4 border-b">
                    <h3 class="text-lg font-semibold">确认删除</h3>
                </div>
                <div class="p-4">
                    <p>确定要删除这名员工的信息吗？此操作不可撤销。</p>
                </div>
                <div class="flex justify-end p-4 border-t">
                    <button onclick="closeDeleteModal()" class="bg-gray-500 text-white px-4 py-2 rounded-lg hover:bg-gray-600 mr-2">
                        取消
                    </button>
                    <button onclick="confirmDelete()" class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700">
                        确认删除
                    </button>
                </div>
            </div>
        </div>
    </div>
    <script>
        $(function () {
            showPage(1);
            loadDepartments();

            $('#searchEmpName').on('keypress', function(e) {
                if (e.which === 13) {
                    e.preventDefault();
                    showPage(1);
                }
            });
        })
        // 添加员工模态框相关函数
        function openAddModal() {
            document.getElementById('addModal').classList.remove('hidden');

            // 重置头像预览区域（与图片一致）
            const avatarPreview = document.getElementById('avatarPreview');
            avatarPreview.innerHTML = `
        <div class="w-full h-full flex flex-col items-center justify-center">
            <i class="fas fa-camera text-gray-400 text-2xl mb-2"></i>
            <span class="text-sm text-gray-500">点击头像上传照片</span>
        </div>
    `;
            avatarPreview.className = 'w-32 h-32 rounded-full bg-gray-100 border-2 border-dashed border-gray-300 flex items-center justify-center cursor-pointer';

            // 重置表单
            document.getElementById('name').value = '';
            document.getElementById('department').selectedIndex = 0;
            document.getElementById('position').value = '';
            document.getElementById('joinDate').value = '';
            document.getElementById('phone').value = '';
        }

        function closeAddModal() {
            document.getElementById('addModal').classList.add('hidden');
        }

        function saveEmployee() {
            // 收集表单数据
            const formData = new FormData();
            formData.append('method', 'add');
            formData.append('name', document.getElementById('name').value);
            formData.append('department', document.getElementById('department').value);
            formData.append('position', document.getElementById('position').value);
            formData.append('joinDate', document.getElementById('joinDate').value);
            formData.append('phone', document.getElementById('phone').value);

            // 添加头像文件
            const avatarFile = document.getElementById('avatar').files[0];
            if (avatarFile) {
                formData.append('avatar', avatarFile);
            } else {
                // 如果没有选择文件，添加默认头像标识
                formData.append('avatar', 'default.jpg');
            }

            // 发送请求
            $.ajax({
                url: 'http://localhost:25080/empsss_war/employee',
                type: 'POST',
                data: formData,
                processData: false,  // 告诉jQuery不要处理数据
                contentType: false,  // 告诉jQuery不要设置Content-Type请求头
                success: function(response) {
                    console.log(response);
                    if(response) {
                        alert("添加成功");
                        closeAddModal();
                        showPage(1); // 刷新列表
                    } else {
                        alert("添加失败");
                    }
                },
                error: function(xhr, status, error) {
                    console.error("添加员工失败:", error);
                    alert("添加员工失败: " + error);
                }
            });
        }

        // 编辑员工模态框相关函数
        let currentEditEmployeeId = null;

        function openEditModal(employeeId) {
            currentEditEmployeeId = employeeId;

            // 获取员工信息
            $.ajax({
                url: 'http://localhost:25080/empsss_war/employee',
                type: 'POST',
                data: {
                    method: 'edit',
                    editModal: employeeId
                },
                dataType: 'json',
                success: function(response) {
                    // 填充表单数据
                    document.getElementById('editName').value = response.empName;
                    document.getElementById('editPosition').value = response.position;
                    document.getElementById('editJoinDate').value = response.onboarding;
                    document.getElementById('editPhone').value = response.phone;

                    // 设置部门选择
                    $('#editDepartment').val(response.deptId);

                    // 设置头像预览
                    const editAvatarPreview = document.getElementById('editAvatarPreview');
                    if(response.imgUrl) {
                        editAvatarPreview.innerHTML = `<img src="${response.imgUrl}" alt="头像预览" class="w-full h-full rounded-full object-cover">`;
                    } else {
                        editAvatarPreview.innerHTML = '<i class="fas fa-user text-gray-400 text-6xl"></i>';
                    }

                    // 显示模态框
                    document.getElementById('editModal').classList.remove('hidden');
                },
                error: function(xhr, status, error) {
                    console.error("获取员工信息失败:", error);
                    alert("获取员工信息失败");
                }
            });
        }

        function closeEditModal() {
            document.getElementById('editModal').classList.add('hidden');
            currentEditEmployeeId = null;
        }

        function updateEmployee() {
            if (!currentEditEmployeeId) return;

            const formData = new FormData();
            formData.append('method', 'update');
            formData.append('id', currentEditEmployeeId);
            formData.append('editName', document.getElementById('editName').value);
            formData.append('editDepartment', document.getElementById('editDepartment').value);
            formData.append('editPosition', document.getElementById('editPosition').value);
            formData.append('editJoinDate', document.getElementById('editJoinDate').value);
            formData.append('editPhone', document.getElementById('editPhone').value);

            // 添加头像文件
            const avatarFile = document.getElementById('editAvatar').files[0];
            if (avatarFile) {
                formData.append('editAvatar', avatarFile);
            }

            $.ajax({
                url: 'http://localhost:25080/empsss_war/employee',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if(response) {
                        alert("更新成功");
                        closeEditModal();
                        showPage(1); // 刷新列表
                    } else {
                        alert("更新失败");
                    }
                },
                error: function(xhr, status, error) {
                    console.error("更新员工失败:", error);
                    alert("更新员工失败: " + error);
                }
            });
        }

        // 删除确认相关函数
        let employeeToDelete = null;

        function showDeleteConfirm(employeeId) {
            employeeToDelete = employeeId;
            document.getElementById('deleteModal').classList.remove('hidden');
        }

        function closeDeleteModal() {
            document.getElementById('deleteModal').classList.add('hidden');
            employeeToDelete = null;
        }

        function confirmDelete() {
            if (!employeeToDelete) return;

            $.ajax({
                url: 'http://localhost:25080/empsss_war/employee',
                type: 'POST',
                data: {
                    method: 'delete',
                    employeeId: employeeToDelete
                },
                success: function(response) {
                    if(response) {
                        alert("删除成功");
                        closeDeleteModal();
                        showPage(1); // 刷新列表
                    } else {
                        alert("删除失败");
                    }
                },
                error: function(xhr, status, error) {
                    console.error("删除员工失败:", error);
                    alert("删除员工失败: " + error);
                }
            });
        }

        // 头像预览函数
        function previewAvatar(input) {
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const avatarPreview = document.getElementById('avatarPreview');
                    avatarPreview.innerHTML = `<img src="${e.target.result}" alt="头像预览" class="w-full h-full rounded-full object-cover">`;
                    avatarPreview.classList.remove('bg-gray-200', 'flex', 'items-center', 'justify-center');
                }
                reader.readAsDataURL(input.files[0]);
            }
        }

        function previewEditAvatar(input) {
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const editAvatarPreview = document.getElementById('editAvatarPreview');
                    editAvatarPreview.innerHTML = `<img src="${e.target.result}" alt="头像预览" class="w-full h-full rounded-full object-cover">`;
                    editAvatarPreview.classList.remove('bg-gray-200', 'flex', 'items-center', 'justify-center');
                }
                reader.readAsDataURL(input.files[0]);
            }
        }

        function showPage(pageNum) {
            $.ajax({
                url: 'http://localhost:25080/empsss_war/employee',
                type: 'POST',
                data: {
                    method: 'list',
                    pageNum: pageNum,
                    empName: $('#searchEmpName').val()
                },
                dataType: 'json',
                success: function(response) {
                    console.log(response);
                    $('tbody').empty();
                    for (const employee of response.data) {
                        if(employee.imgUrl==null || employee.imgUrl==""){
                            employee.imgUrl = "${pageContext.request.contextPath}/img/default.jpg"
                        }
                        let imgUrl = "/empsss_war/"+employee.imgUrl;
                        let tr = `
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap">` + employee.id + `</td>
                            <td class="px-6 py-4 whitespace-nowrap">` + employee.empName + `</td>
                            <td class="px-6 py-4 whitespace-nowrap">` + employee.department.deptName + `</td>
                            <td class="px-6 py-4 whitespace-nowrap">` + employee.position + `</td>
                            <td class="px-6 py-4 whitespace-nowrap">` + employee.onboarding + `</td>
                            <td><img src="`+ imgUrl + `" alt="员工头像" class="img-fluid" width="50"></td>
                            <td>` + employee.phone + `</td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <button onclick="openEditModal(` + employee.id + `)" class="text-blue-600 hover:text-blue-900 mr-3">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button onclick="showDeleteConfirm(${employee.id})" class="text-red-600 hover:text-red-900">
                            <i class="fas fa-trash"></i>
                        </button>
                            </td>
                        </tr>
                        `;
                        $('tbody').append(tr);
                    }
                    // 清空分页导航
                    $('#pageNav').empty();

                    let pageup;
                    if(response.pageNum == 1){
                        pageup = `
                        <li class="page-item disabled">
                            <a class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50" href="#" tabindex="-1">上一页</a>
                        </li>
                        `;
                    } else {
                        pageup = `
                        <li class="page-item">
                            <a class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50" href="#" onclick="showPage(` + (response.pageNum - 1) + `)">上一页</a>
                        </li>
                        `;
                    }
                    $('#pageNav').append(pageup);

                    // 添加页码按钮
                    for(let i=1; i<=response.totalPage; i++){
                        if(i == response.pageNum){
                            $('#pageNav').append(`
                <li class="page-item active">
                    <a class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50" href="#">`+i+`</a>
                </li>
            `);
                        }else{
                            $('#pageNav').append(`
                <li class="page-item">
                    <a class="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50" href="#" onclick="showPage(`+i+`)">`+i+`</a>
                </li>
            `);
                        }
                    }
                    // 下一页按钮
                    let pagedown;
                    if(response.pageNum == response.totalPage){
                        pagedown = `
                            <li class="page-item disabled">
                                <a class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50" href="#">下一页</a>
                            </li>
                            `;
                    } else {
                        pagedown = `
                            <li class="page-item">
                                <a class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50" href="#" onclick="showPage(` + (response.pageNum + 1) + `)">下一页</a>
                            </li>
                            `;
                    }
                    $('#pageNav').append(pagedown);
                },
                error: function(xhr, status, error){
                    console.error("获取员工数据失败:", error);
                }
            });
        }

        function loadDepartments() {
            $.ajax({
                url: 'http://localhost:25080/empsss_war/department',
                type: 'post',
                dataType: 'json',
                success: function(departments) {
                    const deptSelect = $('#department, #editDepartment');
                    deptSelect.empty();
                    deptSelect.append('<option value="">请选择部门</option>');
                    departments.forEach(function(dept) {
                        deptSelect.append(`<option value="${dept.id}">${dept.deptName}</option>`);
                    });
                },
                error: function(xhr, status, error) {
                    console.error("获取部门数据失败:", error);
                    // 如果获取失败，保留默认选项
                    const deptSelect = $('#deptId');
                    deptSelect.empty();
                    deptSelect.append('<option value="">请选择部门</option>');
                    deptSelect.append('<option value="1">技术部</option>');
                    deptSelect.append('<option value="2">人事部</option>');
                    deptSelect.append('<option value="3">市场部</option>');
                }
            });
        }

    </script>
</body>
</html> 